package com.jxc.jxcmanage.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;

/**
 * http工具类
 * @author Jeremy Xiong<br>
 * 2018-11-13 15:46
 */
public class HttpUtil {
    private static Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);
    private static final String Encoding = Charset.defaultCharset().name();

    public static HttpServletResponse getHttpServletResponse() {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        return ((ServletRequestAttributes)ra).getResponse();
    }
    public static HttpServletRequest getHttpServletRequest() {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        return ((ServletRequestAttributes)ra).getRequest();
    }

    public static HttpSession getHttpSession () {
        return getHttpServletRequest().getSession();
    }

    /**
     * web下载方式
     * @param file
     * @param response
     * @return
     */
	public static boolean httpDownload(File file, HttpServletResponse response) {
		try (FileInputStream fis = new FileInputStream(file); OutputStream os = response.getOutputStream()) {
			response.setCharacterEncoding(Encoding);
			response.setContentType("application/x-httpDownload");
			response.addHeader("Content-Disposition",
					"attachment;filename=" + URLEncoder.encode(file.getName(), Encoding));
			byte[] buffer = new byte[1024];
			int bytesToRead;
			while ((bytesToRead = fis.read(buffer)) != -1) {
				os.write(buffer, 0, bytesToRead);
			}
		} catch (IOException e) {
			LOGGER.error("http下载文件出现IO异常", e);
			return false;
		}

		return true;
	}

    /**
     * set http header
     *
     * @param os
     * @param fileName
     * @param response
     */
    public static void setReponseHeader (String fileName, HttpServletResponse response) {
        response.setCharacterEncoding(Encoding);
        response.setContentType("application/x-msdownload");
        try {
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, Encoding));
        } catch (UnsupportedEncodingException e) {
            // nothing
        }
    }
}
